from django.core.management import BaseCommand, CommandParser
import eventlet
import os
import sys
from apps.udpserver.server import HandleUDPConnect
from django.utils.log import request_logger
import socket
from django.utils.autoreload import run_with_reloader

eventlet.monkey_patch(thread=False)


class Command(BaseCommand):
    # 最大接受8000个请求
    handle_pool = eventlet.GreenPool(size=8000)
    handle_connect = HandleUDPConnect()

    def add_arguments(self, parser: CommandParser):
        parser.add_argument(
            '-addr',
            default='127.0.0.1',
            type=str,
            required=False
        )
        parser.add_argument(
            '-port',
            default=9001,
            type=int,
            required=False
        )
        parser.add_argument(
            '-process',
            default=2,
            type=int,
            required=False
        )
        parser.add_argument(
            '-reload',
            default=False,
            type=bool,
            required=False
        )

    def handle(self, *args, **options):
        addr = options['addr']
        port = options['port']

        # 使用eventlet  eventlet默认使用epool 后期无需提升性能使用epool
        listen: socket = socket.socket(family=socket.AF_INET,type=socket.SOCK_DGRAM)
        listen.bind((addr,port))
        request_logger.info('udp server is listen on %s %s' % (addr, port))
        request_logger.info('main process is %s' % (os.getpid()))

       
        # self._start_task_loop()

        def _start():
            
            self.handle_connect(listen)

        if options['reload']:
            run_with_reloader(_start)

        else:
            _start()

    # def _start_task_loop(self):
        # eventlet.spawn(handle_connect.start_heartbeat)
        # eventlet.spawn(self.handle_connect.sub)
